package com.fly.caihong.utils;


import android.content.Context;
import android.os.Environment;

import com.alibaba.fastjson.JSON;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class DataHandler {

    public static final File EXTERNAL_STORAGE_PATH = Environment.getExternalStorageDirectory();
    public static Map<String, String> dataPaths = new HashMap<>();

    public static void copyFilesFromAssets(Context context, String assetsPath, String savePath) {
        try {
            String fileNames[] = context.getAssets().list(assetsPath);// 获取assets目录下的所有文件及目录名
            if (fileNames.length > 0) {// 如果是目录
                File file = new File(savePath);
                file.mkdirs();// 如果文件夹不存在，则递归
                for (String fileName : fileNames) {
                    copyFilesFromAssets(context, assetsPath + "/" + fileName,
                            savePath + "/" + fileName);
                }
            } else {// 如果是文件
                InputStream is = context.getAssets().open(assetsPath);
                FileOutputStream fos = new FileOutputStream(new File(savePath));
                byte[] buffer = new byte[1024];
                int byteCount = 0;
                while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
                    // buffer字节
                    fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
                }
                fos.flush();// 刷新缓冲区
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static boolean handleAppJsonData(String path) {
        String data = FileIOUtils.readFile2String(path, "utf-8");
        dataPaths = (Map) JSON.parseObject(data);
        return dataPaths != null;
    }

    public static <T> void saveJsonData(String pathKey, T t) {
        FileIOUtils.writeFileFromString(EXTERNAL_STORAGE_PATH + dataPaths.get(pathKey), JSON.toJSONString(t));
    }

    public static <T> T convertJsonData(String pathKey, Class<T> clazz) {
        try {
            String pathContent = FileIOUtils.readFile2String(EXTERNAL_STORAGE_PATH + dataPaths.get(pathKey), "utf-8");
            return JSON.parseObject(pathContent, clazz);
        } catch (Exception e) {
            ToastUtils.showLong("数据结构有误：" + clazz);
        }
        return null;
    }

    public static <T> T convertJsonData(String pathKey, String fileName, Class<T> clazz) {
        try {
            String pathContent = FileIOUtils.readFile2String(EXTERNAL_STORAGE_PATH + dataPaths.get(pathKey) + "/" + fileName, "utf-8");
            return JSON.parseObject(pathContent, clazz);
        } catch (Exception e) {
            ToastUtils.showLong("数据结构有误：" + clazz);
        }
        return null;
    }

}
